<template>
  <div class="service-form-page">
    <div class="page-header">
      <h1>{{ isEdit ? '编辑服务' : '发布新服务' }}</h1>
      <div class="header-actions">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="saveService" :loading="saving">
          {{ isEdit ? '更新服务' : '保存服务' }}
        </el-button>
        <el-button 
          v-if="isEdit && serviceForm.status === 'DRAFT'" 
          type="success" 
          @click="publishService"
          :loading="publishing"
        >
          发布服务
        </el-button>
      </div>
    </div>

    <el-card class="form-card">
      <el-form
        ref="formRef"
        :model="serviceForm"
        :rules="formRules"
        label-width="120px"
        size="large"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务标题" prop="title">
              <el-input
                v-model="serviceForm.title"
                placeholder="请输入服务标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="服务分类" prop="category">
              <el-select v-model="serviceForm.category" placeholder="请选择服务分类">
                <el-option
                  v-for="option in SERVICE_CATEGORY_OPTIONS"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="服务描述" prop="description">
          <el-input
            v-model="serviceForm.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述您的服务内容、特色等"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="服务类型" prop="serviceType">
              <el-select v-model="serviceForm.serviceType" placeholder="请选择服务类型">
                <el-option
                  v-for="option in SERVICE_TYPE_OPTIONS"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="服务价格" prop="price">
              <el-input-number
                v-model="serviceForm.price"
                :min="0"
                :precision="2"
                placeholder="请输入价格"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="原价">
              <el-input-number
                v-model="serviceForm.originalPrice"
                :min="0"
                :precision="2"
                placeholder="可选，用于显示折扣"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务时长">
              <el-input-number
                v-model="serviceForm.durationMinutes"
                :min="0"
                placeholder="服务时长（分钟）"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="服务区域">
              <el-input
                v-model="serviceForm.serviceArea"
                placeholder="请输入服务区域"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input
                v-model="serviceForm.contactPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="联系地址">
              <el-input
                v-model="serviceForm.contactAddress"
                placeholder="请输入联系地址"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="营业时间">
          <el-input
            v-model="serviceForm.businessHours"
            placeholder="例如：周一至周日 8:00-20:00"
          />
        </el-form-item>

        <el-form-item label="服务图片">
          <el-upload
            v-model:file-list="imageFileList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            accept="image/*"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            建议上传3-5张服务相关图片，支持JPG、PNG格式，单张图片不超过2MB
          </div>
        </el-form-item>

        <el-form-item label="服务标签">
          <el-tag
            v-for="tag in serviceTags"
            :key="tag"
            closable
            @close="removeTag(tag)"
            style="margin-right: 8px; margin-bottom: 8px;"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="tagInputVisible"
            ref="tagInputRef"
            v-model="tagInputValue"
            size="small"
            style="width: 100px;"
            @keyup.enter="addTag"
            @blur="addTag"
          />
          <el-button v-else size="small" @click="showTagInput">+ 添加标签</el-button>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="推荐服务">
              <el-switch v-model="serviceForm.isRecommended" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="热门服务">
              <el-switch v-model="serviceForm.isPopular" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="排序权重">
              <el-input-number
                v-model="serviceForm.sortOrder"
                :min="0"
                placeholder="数值越大排序越靠前"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { merchantServiceApi, SERVICE_CATEGORY_OPTIONS, SERVICE_TYPE_OPTIONS } from '@/api/merchantService'

const route = useRoute()
const router = useRouter()

const isEdit = computed(() => !!route.params.id)
const serviceId = computed(() => route.params.id)

const formRef = ref(null)
const tagInputRef = ref(null)
const saving = ref(false)
const publishing = ref(false)
const imageFileList = ref([])
const tagInputVisible = ref(false)
const tagInputValue = ref('')
const serviceTags = ref([])

// 表单数据
const serviceForm = reactive({
  title: '',
  description: '',
  category: '',
  serviceType: '',
  price: null,
  originalPrice: null,
  durationMinutes: null,
  serviceArea: '',
  contactPhone: '',
  contactAddress: '',
  businessHours: '',
  isRecommended: false,
  isPopular: false,
  sortOrder: 0,
  imageUrls: '[]',
  tags: '[]',
  status: 'DRAFT'
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入服务标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入服务描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择服务分类', trigger: 'change' }
  ],
  serviceType: [
    { required: true, message: '请选择服务类型', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入服务价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ]
}

// 加载服务详情
const loadServiceDetail = async () => {
  if (!isEdit.value) return
  
  try {
    const response = await merchantServiceApi.getServiceDetail(serviceId.value)
    const service = response.data
    
    Object.assign(serviceForm, service)
    
    // 解析图片URLs
    try {
      const imageUrls = JSON.parse(service.imageUrls || '[]')
      imageFileList.value = imageUrls.map((url, index) => ({
        uid: index,
        name: `image-${index}`,
        url: url
      }))
    } catch (e) {
      console.error('解析图片URLs失败:', e)
    }
    
    // 解析标签
    try {
      serviceTags.value = JSON.parse(service.tags || '[]')
    } catch (e) {
      console.error('解析标签失败:', e)
    }
  } catch (error) {
    console.error('加载服务详情失败:', error)
    ElMessage.error('加载服务详情失败')
  }
}

// 保存服务
const saveService = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch (error) {
    ElMessage.error('请检查表单填写')
    return
  }
  
  saving.value = true
  try {
    // 准备提交数据
    const submitData = {
      ...serviceForm,
      imageUrls: JSON.stringify(imageFileList.value.map(file => file.url || file.response?.url || '')),
      tags: JSON.stringify(serviceTags.value)
    }
    
    let response
    if (isEdit.value) {
      response = await merchantServiceApi.updateService(serviceId.value, submitData)
    } else {
      response = await merchantServiceApi.createService(submitData)
    }
    
    ElMessage.success(isEdit.value ? '服务更新成功' : '服务创建成功')
    
    if (!isEdit.value) {
      // 新建成功后跳转到编辑页面
      router.replace(`/services/edit/${response.data.id}`)
    }
  } catch (error) {
    console.error('保存服务失败:', error)
    ElMessage.error('保存服务失败')
  } finally {
    saving.value = false
  }
}

// 发布服务
const publishService = async () => {
  try {
    await ElMessageBox.confirm('确定要发布这个服务吗？发布后用户就可以看到并预约了。', '确认发布', {
      type: 'warning'
    })
    
    publishing.value = true
    await merchantServiceApi.publishService(serviceId.value)
    
    serviceForm.status = 'PUBLISHED'
    ElMessage.success('服务发布成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布服务失败:', error)
      ElMessage.error('发布服务失败')
    }
  } finally {
    publishing.value = false
  }
}

// 处理图片变化
const handleImageChange = (file, fileList) => {
  imageFileList.value = fileList
}

// 处理图片移除
const handleImageRemove = (file, fileList) => {
  imageFileList.value = fileList
}

// 显示标签输入框
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

// 添加标签
const addTag = () => {
  const tag = tagInputValue.value.trim()
  if (tag && !serviceTags.value.includes(tag)) {
    serviceTags.value.push(tag)
  }
  tagInputValue.value = ''
  tagInputVisible.value = false
}

// 移除标签
const removeTag = (tag) => {
  const index = serviceTags.value.indexOf(tag)
  if (index > -1) {
    serviceTags.value.splice(index, 1)
  }
}

// 返回
const goBack = () => {
  router.back()
}

onMounted(() => {
  loadServiceDetail()
})
</script>

<style scoped>
.service-form-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.form-card {
  max-width: 1000px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>
